// 通用增删改查子类
import { Injectable } from '@nestjs/common';
import { In } from 'typeorm';

export interface IOptions {
  where?: any;
  skip?: number;
  take?: number;
  order?: any;
  relations?: any;
}

@Injectable()
export class BaseService {
  // 获取列表
  async getLists(options: IOptions = { where: {} }): Promise<any> {
    const page = parseInt(options.where.page) || 1;
    const limit = parseInt(options.where.limit) || 10;
    delete options.where.page;
    delete options.where.limit;
    const obj: any = {
      skip: limit * (page - 1),
      take: limit,
      ...options,
    };
    const [data, count] = await this['module'].findAndCount(obj);
    return {
      lists: data,
      count,
    };
  }

  // 获取所有
  async getAll(options: IOptions = { where: {} }): Promise<any> {
    const [data, count] = await this['module'].findAndCount(options);
    return {
      lists: data,
      count,
    };
  }

  // 获取详情
  async getOne(options: IOptions = { where: {} }): Promise<any> {
    return this['module'].findOne(options);
  }

  // 查到修改操作，否则新增操作
  async createOrUpdate(data): Promise<any> {
    return this['module'].save(data);
  }

  // 物理批量删除
  async delete(query: string): Promise<any> {
    const ids = query.split(',');
    return this['module'].delete(ids);
  }

  // 逻辑批量删除
  async update_delete(query: string): Promise<any> {
    const ids = query.split(',').map((id) => parseInt(id));
    const res = await this['module'].find({
      where: {
        id: In(ids),
      },
    });
    res.forEach((item) => {
      if (item.is_delete) {
        item.is_delete = '1';
        this['module'].save(item);
      }
    });
  }
}
